package com.tinem.platform.web.gateway.filter;

import com.tinem.platform.module.pojo.co.Commons;
import com.tinem.platform.module.pojo.co.RedisKeyEnum;
import com.tinem.platform.module.pojo.vo.error.UserException;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.web.gateway.util.GatewayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className ChannelScopeGatewayFilterFactory
 * @description 客户端请求签名
 * @site 
 * @company 
 * @create 2020-07-03 12:26
 */
@Slf4j
@Component
public class ClientScopeGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            String clientId = GatewayUtil.getClient(exchange);

            String service = GatewayUtil.getApiService(exchange);
            if(stringRedisTemplate.opsForSet().isMember(RedisKeyEnum.channel_scope.getKey(clientId), service)){
                return chain.filter(exchange);
            }

            if (stringRedisTemplate.opsForSet().isMember(RedisKeyEnum.channel_scope.getKey(clientId), Commons.ROOT_AUTHORIZE)) {
                return chain.filter(exchange);
            }
            throw new UserException(MessageCode.ERROR_PLATFORM_CLOUD_WEB_GATEWAY_SCOPE_NOT_FIND,service);
        };
    }
}
